package com.bjut.vendormgrsys.web.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bjut.vendormgrsys.constant.Constant.UserStatus;
import com.bjut.vendormgrsys.service.CampaignService;
import com.bjut.vendormgrsys.service.MailService;
import com.bjut.vendormgrsys.service.UserService;
import com.bjut.vendormgrsys.support.bo.UserBO;
import com.bjut.vendormgrsys.util.DateUtils;
import com.bjut.vendormgrsys.util.HttpUtil;
import com.bjut.vendormgrsys.util.PwdUtils;
import com.bjut.vendormgrsys.web.dto.*;
import com.bjut.vendormgrsys.web.dto.other.ResultRoleInfoList;
import com.bjut.vendormgrsys.web.dto.other.ResultRoleInfoListData;
import com.bjut.vendormgrsys.web.dto.user.*;
import com.google.gson.JsonObject;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class AiApiController implements AiApi {

    private static final Logger log = LoggerFactory.getLogger(AiApiController.class);

    @Override
    public ResponseEntity<ResultInfo> xfApi(AiBody body) {
        ResponseEntity<ResultInfo> entity;
        try {
            String url = "https://spark-api-open.xf-yun.com/v1/chat/completions";
            Map<String,String> headers = new HashMap<>();
            headers.put("Content-Type","application/json");
            headers.put("Authorization","Bearer c76a8f98cbec7789ef918923d2b9b487:ODUyZTRlZmI0ZDA1OGRhMGYyOTg2MGY4");

            Map<String,Object> requests = new HashMap<>();
            requests.put("model","generalv3.5");//取值为[general,generalv2,generalv3,generalv3.5,4.0Ultra]
//        requests.put("stream",false);//是否开启流式传输,默认False
//        requests.put("temperature",0.5f);//取值范围 (0，1] ，默认值0.5	,核采样阈值。用于决定结果随机性，取值越高随机性越强即相同的问题得到的不同答案的可能性越高
//        requests.put("max_tokens",4096);//取值为[1,8192]，默认为4096。模型回答的tokens的最大长度
//        requests.put("top_k",4);//取值为[1，6],默认为4	,从k个候选中随机选择⼀个（⾮等概率）
            List<Map<String,String>> messages = new ArrayList<>();
            Map<String,String> mes = new HashMap<>();
            mes.put("role","user");//system用于设置对话背景，user表示是用户的问题，assistant表示AI的回复
            mes.put("content",body.getContext());//所有content的累计tokens需控制8192以内
            messages.add(mes);
            requests.put("messages",messages);
            String result = HttpUtil.doPost(url, JSONObject.toJSONString(requests),headers);
            System.out.println(result);
            JSONObject json = JSONObject.parseObject(result);

            if(json.getInteger("code")!=0)
                return new ResponseEntity<>(new ResultInfo().code(HttpStatus.INTERNAL_SERVER_ERROR.value()).message("讯飞接口状态异常：" + json.getInteger("code")), HttpStatus.INTERNAL_SERVER_ERROR);
            JSONArray arrays = json.getJSONArray("choices");
            if(arrays==null || arrays.size()<=0)
                return new ResponseEntity<>(new ResultInfo().code(HttpStatus.INTERNAL_SERVER_ERROR.value()).message("讯飞接口无返回："), HttpStatus.INTERNAL_SERVER_ERROR);

            return new ResponseEntity<>(new ResultInfo().code(HttpStatus.OK.value()).message("成功").data(arrays.getJSONObject(0).getJSONObject("message").get("content")), HttpStatus.OK);
        } catch (Exception e) {
            log.error("讯飞接口异常：", e);
            return new ResponseEntity<>(new ResultInfo().code(HttpStatus.INTERNAL_SERVER_ERROR.value()).message("讯飞接口异常：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
